// pages/cart/index.js
import regeneratorRuntime from '../../lib/runtime/runtime'
import {getSetting,chooseAddress,openSetting,showModal,showToast} from '../../utils/asyncWx'
Page({
    data:{
        address:{},
        cart:[],
        allChecked:false,
        totalPrice:0,
        totalNum:0,
    },
    onShow(){
     const address=wx.getStorageSync("address");
     const cart =wx.getStorageSync("cart")||[];
    this.setCart(cart);
       this.setData({
           address,
       })
    },

   async handleChooseAddress(){
       const res1 =await getSetting();
       const scopeAddress=res1.authSetting["scope.adderss"]; 
        if(scopeAddress===true||scopeAddress===undefined){
        
             const address=await chooseAddress();
              wx.setStorageSync("address", address);
        }else{
            await openSetting();
              const address=await chooseAddress();
              wx.setStorageSync("address", address);
                
        }
       
         
   },
   handleItemChange(e){
     const goods_id=e.currentTarget.dataset.id;
     let {cart}=this.data
     let index=cart.findIndex(v=>v.goods_id===goods_id)
     cart[index].checked=!cart[index].checked
        this.setCart(cart);
     },
   handleItemAllCheck(){
    let {cart,allChecked}=this.data
    allChecked=!allChecked
    cart.forEach(v=>{
        v.checked=allChecked
    })
    this.setCart(cart)
   },
   async handleItemNumEdit(e){
       let {cart} =this.data
     const id=e.currentTarget.dataset.id
     const operation=e.currentTarget.dataset.operation
      const index=cart.findIndex(v=>v.goods_id===id)
      if(cart[index].num===1&&operation===-1){
          const res=await showModal({content:'你是不是要删除？'})
          if(res.confirm){
            cart.splice(index,1)
            this.setCart(cart)
          }
        }else{
              cart[index].num+=operation
               this.setCart(cart)  
          }
    
   },
   setCart(cart){
       
        let totalPrice=0;
     let totalNum=0;
     const allChecked=cart.length?cart.every(v=>v.checked):false
    cart.forEach(v=> {
        if(v.checked){
            totalPrice+=v.num*v.goods_price
            totalNum+=v.num
        }

    });
     this.setData({
         cart,
         totalPrice,
         totalNum,
          allChecked
     })
      wx.setStorageSync("cart", cart);
   },
 async  handlePay(){
       const {address,totalNum}=this.data
       if(!address.userName){
        await showToast({title:'选地址啊，老板！'})
           return
       }
       if(totalNum===0){
           await showToast({title:"你没有选东西啊"})
           return
       }
       wx.navigateTo({
           url: '/pages/pay/index',
        
       });
         
   }
  

})